#!/bin/sh
#
#params: distrib arch branch section

NOW=$(/bin/date '+%Y%m%d-%H%M')

echo "=== Setting environment ==="

export MPHS_HOME="/home/mephisto"
export MPHS_DATA="$MPHS_HOME/data"
export MPHS_PKG_EXTRACTION="$MPHS_HOME/package-extractor/"
export MPHS_MIRROR="/home/mirror"
export MPHS_LOG="$MPHS_HOME/logs/"
export MPHS_MYSQL_USER="root"
export MPHS_MYSQL_PASSWORD="oggvorbis"
export MPHS_DATABASE="mephisto"
export PATH="$PATH:$MPHS_PKG_EXTRACTION/"
export VENDOR="mandriva"
export DISTRIBUTION=$1
export ARCH=$2
if [ $2 == "SRPMS" ]; then
    export MEDIA=""
else
    export MEDIA="media"
fi
export BRANCH=$3
export SECTION=$4

echo ""
echo "=== Computing package diff ==="
groovy $MPHS_PKG_EXTRACTION/package_diff_generator $MPHS_MIRROR/$VENDOR/$DISTRIBUTION/$ARCH/$MEDIA/$BRANCH/$SECTION/ $MPHS_DATA/$VENDOR-$DISTRIBUTION-$ARCH-$BRANCH-$SECTION/ $MPHS_LOG/$VENDOR-$DISTRIBUTION-$ARCH-$BRANCH-$SECTION.added.list.${NOW} $MPHS_LOG/$VENDOR-$DISTRIBUTION-$ARCH-$BRANCH-$SECTION.remov.list.${NOW} $MPHS_LOG/mphs.log.${NOW}

echo ""
echo "=== Removing diff packages metadata ==="
groovy $MPHS_PKG_EXTRACTION/package_diff_metadata_eraser $MPHS_DATA/$VENDOR-$DISTRIBUTION-$ARCH-$BRANCH-$SECTION/ $MPHS_LOG/$VENDOR-$DISTRIBUTION-$ARCH-$BRANCH-$SECTION.remov.list.${NOW} $MPHS_LOG/mphs.log.${NOW}

echo ""
echo "=== Generating diff packages sql command ==="
groovy $MPHS_PKG_EXTRACTION/package_diff_sql_generator $DISTRIBUTION $MPHS_LOG/$VENDOR-$DISTRIBUTION-$ARCH-$BRANCH-$SECTION.remov.list.${NOW} $MPHS_LOG/$VENDOR-$DISTRIBUTION-$ARCH-$BRANCH-$SECTION.remove.sql.${NOW} $MPHS_LOG/mphs.log.${NOW}

echo ""
echo "=== Executing diff packages sql command ==="
mysql -u $MPHS_MYSQL_USER -p$MPHS_MYSQL_PASSWORD $MPHS_DATABASE < $MPHS_LOG/$VENDOR-$DISTRIBUTION-$ARCH-$BRANCH-$SECTION.remove.sql.${NOW} > $MPHS_LOG/mysql.delete.log 

echo ""
echo "=== Extracting diff packages ==="
python $MPHS_PKG_EXTRACTION/package-list-extractor.py --distrib=$DISTRIBUTION --arch=$ARCH --branch=$BRANCH --section=$SECTION --inputdir=$MPHS_MIRROR/$VENDOR/$DISTRIBUTION/$ARCH/$MEDIA/$BRANCH/$SECTION/ --outputdir=$MPHS_DATA/$VENDOR-$DISTRIBUTION-$ARCH-$BRANCH-$SECTION/ --metadata-only=false --log=$MPHS_LOG/mphs.log.${NOW}

echo ""
echo "=== Converting diff packages metadata to csv ==="
groovy $MPHS_PKG_EXTRACTION/package_metadata_to_csv.groovy $MPHS_DATA/$VENDOR-$DISTRIBUTION-$ARCH-$BRANCH-$SECTION/ ${NOW} $MPHS_LOG $MPHS_LOG/mphs.log.${NOW} $MPHS_LOG/$VENDOR-$DISTRIBUTION-$ARCH-$BRANCH-$SECTION.added.list.${NOW}

echo""
echo "=== Loading diff packages metadata in the database ==="
mysql -u $MPHS_MYSQL_USER -p$MPHS_MYSQL_PASSWORD $MPHS_DATABASE < $MPHS_PKG_EXTRACTION/load-package-data.sql > $MPHS_LOG/mysql.load.log
